/*
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fs from "node:fs";
import path from "node:path";
import { tsRules } from "../visitor.config.js";
import {
  makeFile,
  getFileName,
  validFileExist,
  isAllRule,
} from "../utils/index.js";
import { processTSRule } from "./processArkUiCode.js";

const processDuplicate = (list = []) => {
  const result = [];
  const map = new Map();
  for (const item of list) {
    const { buggyFilePath, mainBuggyLine, defectType } = item;
    const key = `${buggyFilePath}-${mainBuggyLine}-${defectType}`;
    if (!map.has(key)) {
      result.push(item);
      map.set(key, 1);
    }
  }
  return result;
};

const main = (options) => {
  const filePaths = options.get("--path") || "";
  const rule = options.get("--checker") || "";
  const out = options.get("--output") || "";

  let checkItems = [];
  if (filePaths === "") {
    console.log(
      `Error: Please ser parser files. eg: --path "./example.ts,./xxx.ts"`
    );
    return false;
  }
  if (out === "") {
    console.log(
      `Error: Please set output dir. eg: --output "./result/result.json"`
    );
    return false;
  }
  const fileList = filePaths.split(",");
  const rules = rule.replace(/，/, ",");

  // ==========================================================
  console.log(` ************ Task Start ************* `);
  console.log(` Total files: ${fileList.length} `);
  console.log(` Checker: ${rules} `);

  const ruleList = rules.split(",");
  const curTsRules = isAllRule(rule)
    ? tsRules
    : tsRules.filter((x) => ruleList.includes(x.checker));
  // 先处理babelRules，再处理tsRules
  for (let i = 0; i < fileList.length; i++) {
    console.log(`【${i + 1}/${fileList.length}】 Parse: ${fileList[i]}`);
    if (!validFileExist(fileList[i])) {
      continue;
    }
    const code = fs.readFileSync(path.resolve(fileList[i]), "utf-8").toString();
    // 处理tsRules
    if (curTsRules.length > 0) {
      processTSRule({ curTsRules, checkItems, code, file: fileList[i] });
    }
  }

  // ========================================================
  console.log(` ************* Task End ***************`);
  // 对检查结果去重
  checkItems = processDuplicate(checkItems);

  // 生成文件
  makeFile(out, checkItems);
  const { outPath, outName } = getFileName(out);
  console.log(`Done, output dir see : ${path.resolve(outPath, outName)}`);
};

export { main };
